package com.rk.section1;

import java.text.DecimalFormat;
import java.text.Format;
import java.util.Map;

/**
 * 重构书籍中的第一个例子：戏剧演出团打印账单详情
 */
public class Statement {

    /**
     * 根据观众人数和剧目类型收费
     * 根据观众人数发放积分，下次可以使用积分获得折扣
     *
     * @param invoice 账单
     * @param plays 剧目
     * @return 账单文字内容
     */
    public String statement(Invoice invoice, Map<String, Play> plays) {
        int totalAmount = 0;
        int volumeCredits = 0;
        /*
         * result记录账单文字内容 用于最终返回
         */
        StringBuilder result = new StringBuilder();
        result.append(String.format("Statement for %s\n",invoice.getCustomer()));
        final Format format = new DecimalFormat("$,###.00");

        /*
         * 循环计算总费用、积分
         */
        for (Performance performance : invoice.getPerformances()) {
            final Play play = plays.get(performance.getPlayID());
            int thisAmount;
            /*
             * 不同类型 不同收费方案
             */
            switch (play.getType()) {
                case "tragedy":
                    thisAmount = 40000;
                    if (performance.getAudience() > 30) {
                        thisAmount += 1000 * (performance.getAudience() - 30);
                    }
                    break;
                case "comedy":
                    thisAmount = 30000;
                    if (performance.getAudience() > 20) {
                        thisAmount += 10000 + 500 * (performance.getAudience() - 20);
                    }
                    thisAmount += 300 * performance.getAudience();
                    break;
                default:
                    throw new Error("unknown type：" + play.getType());
            }

            /*
             * 计算积分
             */
            volumeCredits += Math.max(performance.getAudience() -30 ,0);
            if ("comedy".equals(play.getType())){
                volumeCredits += Math.floor(performance.getAudience() /5.0);
            }

            result.append(String.format("  %s:%s (%d seats)\n",play.getName(),format.format(thisAmount/100),performance.getAudience()));
            totalAmount += thisAmount;
        }
        result.append(String.format("Amout owed is %s\n",format.format(totalAmount/100)));
        result.append(String.format("You earned %scredits\n",volumeCredits));
        return result.toString();
    }

}
